package com.white.FalseWorld;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.white.FalseWorld.sqllist.UserbaseHelper;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import static java.sql.DriverManager.getConnection;

/**
 * 作者：white
 * 时间：2020/10/1.
 */
public class LoginActivity extends AppCompatActivity {

    private EditText username,password;
    private Button login;
    private String user="",pass;
    private UserbaseHelper dbhelper;
    //临时变量，用户数据库查询的获取
    String temp_user="";
    String temp_pass="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_login );
        //绑定组件
        username=findViewById( R.id.username );
        password=findViewById( R.id.password );
        login=findViewById( R.id.login );

        //登录功能
        login.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                user= username.getText().toString();
                pass=password.getText().toString();
                connection_mysql();
                saveSqlList();
            }
        } );

        dbhelper = new UserbaseHelper(this, "FalseWorld_user.db", null, 1);
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        Cursor cursor = db.query("FalseWorld_user", null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                user=cursor.getString(cursor.getColumnIndex("username")) ;
            } while (cursor.moveToNext());
        }
        cursor.close();
        if (user.length()!=0){
            Intent intent=new Intent( LoginActivity.this,IndexActivity.class);
            intent.putExtra( "user",user );
            startActivity( intent );
            finish();
        }


    }

    private void saveSqlList() {
//        SharedPreferences.Editor editor=getSharedPreferences( "FalseWorld_user", Context.MODE_PRIVATE ).edit();
//        editor.putString( "username",user );
//        editor.apply();
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put( "username",user );
        db.insert("FalseWorld_user", null, values);
    }


    private void connection_mysql() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    /**
                     * 访问数据库，如果不存在则自动创建新账号，存在则判断密码是否正确，正确调往功能界面
                     */

                    Class.forName("com.mysql.jdbc.Driver");
                    System.out.println("这边这边这边这边");
                    Connection cn= getConnection( getString( R.string.mysql_address ),getString( R.string.mysql_username ),getString( R.string.mysql_password ));
                    System.out.println("连接数据库成功");
                    String sql="SELECT user_wx FROM personals WHERE user_wx= '"+user+"'";
                    Statement st=(Statement)cn.createStatement();
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        temp_user=rs.getString("user_wx");
                    }
                    System.out.println( "取出来的值"+temp_user );
                    if (temp_user.length()==0|temp_user.equals( "null" )|temp_user.equals( "" )){
                        sql="INSERT into personals VALUES (NULL,'"+user+"','"+pass+"','"+user+"',null,0,null,null)";
                        if (st.executeUpdate( sql )!=0){
                            System.out.println( "注册成功" );
                        }else{
                            System.out.println( "注册失败" );
                        }
                    }
                    // 注册或登录后，进行账号对应密码的校队
                    // 如果正确证明登录成功，带着账号进行activity的跳转
                    sql="SELECT * FROM personals WHERE user_wx= '"+user+"'";
                    rs=st.executeQuery(sql);
                    while(rs.next()){
                        temp_pass=rs.getString("password");
                    }

                    cn.close();
                    st.close();
                    rs.close();

                    /**
                     * 以微信号发送页面
                     * 判断密码是否正确，再判断头像跟标签是为空，如果为空判断为新注册用户，需要跳转页面填写信息
                     */
                    if (temp_pass.equals( pass )){

                            //跳转信息填写页面
                            Intent intent=new Intent( LoginActivity.this,LoginStepActivity.class);
                            intent.putExtra( "user",user );
                            startActivity( intent );


                    }else{
                        Looper.prepare();
                        Toast.makeText( LoginActivity.this,"密码错误，请重新输入。",Toast.LENGTH_SHORT ).show();
                        Looper.loop();
                    }
                } catch (Exception e) {
                    System.out.println("连接数据库失败");
                    e.printStackTrace();
                }
            }
        } ).start();

    }



}